﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Autofac;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.IService.JJFlow;
using Jinjia.Approve.IService.JJFlow.Condition;

namespace Jinjia.Approve.Service.JJFlow
{
    public class JJFlowStepService : IJJFlowStepService
    {
        private readonly IFlowStepRepository _flowStepRepository;
        private readonly IComponentContext _componentContext;

        public JJFlowStepService(IFlowStepRepository flowStepRepository, IComponentContext componentContext)
        {
            _flowStepRepository = flowStepRepository;
            _componentContext = componentContext;
        }

        public async Task<List<jj_flow_step>> GetNextPossiblePath(int node_id)
        {
            return await _flowStepRepository.GetNextPossiblePath(node_id);
        }

        /// <summary>
        /// 根据设置的条件判断名称condition_name、以及外部业务主键biz_order_id进行判断是否条件满足
        /// 
        /// </summary>
        /// <param name="biz_order_id"></param>
        /// <param name="step_id"></param>
        /// <param name="depart_id"></param>
        /// <param name="user_id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> ConditionSatisfied(string biz_order_id, int step_id, string depart_id = "0", string user_id = "0")
        {
            var jjFlowStep = await _flowStepRepository.GetById(step_id);
            var resolveResult = _componentContext.TryResolveNamed(jjFlowStep.condition_name, typeof(IJJCondition), out var service);
            if (resolveResult)
            {
                var orderService = (IJJCondition)service;
                return await orderService.IsSatisfied(biz_order_id, depart_id, user_id);
            }

            throw new NotImplementedException($"找不到[{jjFlowStep.condition_name}]对应的类型!");
        }
    }
}